<template>
  <view class="container">
    <!-- 轮播图 -->
    <swiper class="swiper" interval="3000">
      <swiper-item v-for="(item, index) in carouselImages" :key="index">
        <image :src="item" class="swiper-image"/>
      </swiper-item>
    </swiper>
    <!-- 当前用车,行程列表 -->
    <uni-group
        v-if="currentCarRequest"
        mode="line" title="当前用车">
      <view>
        <view>
          <uni-section type="line" title="当前用车申请">
            <uni-list :border="false">
              <!-- 当前用车或申请用车按钮 -->
              <view class="current-car">
                <view v-if="currentCarRequest">
                  <uni-group mode="card" :title="currentCarRequest?'正在进行中的用车':'没有安排哦！'">
                    <view class="CarRequest-card">
                      <view>
                        <image :src="currentCarRequest?.user.avatarUrlWbxqy" class="avatar"/>
                      </view>
                      <view class="info">
                        <text class="username">{{ currentCarRequest?.user.usernameWbxqy }}</text>
                        <text class="details">{{ currentCarRequest?.car.brandWbxqy }} -
                          {{ currentCarRequest?.car.modelWbxqy }} -
                          {{ currentCarRequest?.car.licensePlateWbxqy }}
                        </text>
                        <text class="details">司机: {{ currentCarRequest?.driver.usernameWbxqy }}</text>
                        <text class="date">申请日期: {{ currentCarRequest?.requestDateWbxqy }}</text>
                        <text class="date">开始时间: {{ currentCarRequest?.startTimeWbxqy }}</text>
                        <text class="date">结束时间: {{ currentCarRequest?.endTimeWbxqy }}</text>
                        <view style="display: flex;justify-content: space-between;align-items: center;margin-top: 10px">
                          <view>
                            <uni-tag :text="getCarRequestStatusText(currentCarRequest?.statusWbxqy)"/>
                          </view>
                        </view>
                      </view>
                    </view>
                  </uni-group>
                </view>
                <view v-else>
                  <uni-group mode="card" title="无用车申请">
                  </uni-group>
                </view>
              </view>
            </uni-list>
          </uni-section>
          <uni-section type="line" title="行程列表">
            <uni-list :border="false">
              <view>
                <uni-section
                    title="行程"
                    v-for="(item) in currentTripList"
                    :sub-title="item.tripIdWbxqy?.toString().padStart(8, '0')"
                >
                  <uni-list :border="false">
                    <uni-list-item :title="item.startLocationWbxqy" :note="'出发时间:'+item.startTimeWbxqy"/>
                    <uni-list-item :title="item.endLocationWbxqy"
                                   :note="item.endTimeWbxqy===null?'到达时间: 未到达':'到达时间:'+item.endTimeWbxqy"
                                   :rightText="getTripStatusText(item.tripStatusWbxqy)"
                    />
                    <!-- 操作列表  -->
                    <view style="display: flex;justify-content: right">
                      <uni-tag
                          v-if="item.tripStatusWbxqy==='S'"
                          @click="this.$refs.startTripDialog.open();currentTripId=item.tripIdWbxqy"
                          text="开始行程" type="primary" :inverted="true"
                      />
                      <uni-tag
                          v-else-if="item.tripStatusWbxqy==='I'"
                          @click="this.$refs.endTripDialog.open();currentTripId=item.tripIdWbxqy"
                          text="结束行程" type="warning" :inverted="true"
                      />
                      <uni-tag
                          v-else-if="item.tripStatusWbxqy==='E'"
                          text="结束已行程" type="default" :inverted="true"
                          disabled
                      />
                    </view>
                  </uni-list>
                </uni-section>
              </view>
            </uni-list>
          </uni-section>
        </view>
      </view>
      <view>
        <!-- 开始行程 -->
        <uni-popup ref="startTripDialog" type="dialog">
          <uni-popup-dialog ref="inputClose" mode="input" title="上传照片,确保已接到乘客" value="对话框预置提示内容!"
                            placeholder="请输入内容" @confirm="startDialogInputConfirm">
            <view style="padding: 10px;padding-top: 0;width: 100%;display: flex;justify-content: right">
              <uni-file-picker
                  ref="files"
                  @select="select"
                  v-model="imageList"
                  fileMediatype="image"
                  @success="success"
                  limit="1" title="选择1张图片"></uni-file-picker>
            </view>
          </uni-popup-dialog>
        </uni-popup>
        <!-- 结束行程 -->
        <uni-popup ref="endTripDialog" type="dialog">
          <uni-popup-dialog ref="inputClose" mode="input" title="输入里程(km)" value="对话框预置提示内容!"
                            placeholder="里程数,公里" @confirm="endDialogInputConfirm"></uni-popup-dialog>
        </uni-popup>
      </view>
    </uni-group>
    <uni-group v-else mode="line" title="">
      <view v-if="currentDriver.statusWbxqy!=='O'">
        当前没有用车,等待管理员分配
      </view>
      <view v-else style="display: flex; justify-content: space-between; align-items: center;">
        <text>
          外出中...
        </text>
        <uni-tag
            @click="returned()"
            text="已返程" type="primary" :inverted="true"
        />
      </view>

    </uni-group>

  </view>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {getCurrentCarRequest} from "../../api/driverMG";
import {endTrip, getTripList, getUserInfo, returnedAAA, startTrip} from "../../api/tripMG";

// 轮播图图片列表
const carouselImages = ref([
  'http://localhost:9999/img/8a7342f7-b6a3-4867-a580-b1326050a4ec_宁静的绿色极光风景壁纸.jpg',
  'http://localhost:9999/img/969078d4-f888-44b4-9703-a69dde1bfb2c_高山峡谷唯美意境风景壁纸.jpg',
  'http://localhost:9999/img/6c56f90b-0dd0-40c2-810d-fe05d54acf98_冬季美丽的树林唯美桌面壁纸.jpg'
])

// 当前用车信息
const currentCarRequest = ref(null)
const requestId = ref()
const currentTripList = ref(null)
const currentDriver = ref(null)
const endData = ref()

const imageList = ref([])
// 获取当前用车信息
const fetchCurrentCarRequestInfo = async () => {
  try {
    // 请替换为实际的获取当前用车信息的接口
    currentCarRequest.value = await getCurrentCarRequest()
  } catch (error) {
    console.error('当前用车申请加载失败:', error)
  }
}
const fetchTripList = async () => {
  currentTripList.value = await getTripList({
    requestId: requestId.value
  })
}
const fetchUserInfo = async () => {
  currentDriver.value = await getUserInfo();
}
const fetchData = async () => {
  await fetchCurrentCarRequestInfo()
  requestId.value = currentCarRequest.value.requestIdWbxqy
  await fetchTripList()
  await fetchUserInfo()
}
// 在组件挂载时获取数据
onMounted(async () => {
  await fetchData()
  uni.setTabBarItem({
    index: 0,
    visible: false
  })
  uni.setTabBarItem({
    index: 1,
    visible: false
  })
  uni.setTabBarItem({
    index: 2,
    visible: true
  })
  uni.setTabBarItem({
    index: 3,
    visible: true
  })
  uni.setTabBarItem({
    index: 4,
    visible: true
  })
})


// 获取状态文本
const getCarRequestStatusText = (status) => {
  switch (status) {
    case 'S':
      return '待审核'
    case 'A':
      return '已批准'
    case 'R':
      return '已拒绝'
    case 'E':
      return '已结束'
    default:
      return '未知状态'
  }
}
// 获取状态文本
const getTripStatusText = (status) => {
  switch (status) {
    case 'S':
      return '未开始'
    case 'I':
      return '进行中'
    case 'E':
      return '已结束'
    default:
      return '未知状态'
  }
}
// 当前行程
const currentTripId = ref()
// 开始行程
const startDialogInputConfirm = async () => {
  await startTrip({
    "tripIdWbxqy": currentTripId.value,
    "imageUrlWbxqy": currentImageUrl.value
  })
  await fetchData()
}
// 结束行程
const endDialogInputConfirm = async (val) => {
  await endTrip({
    "tripIdWbxqy": currentTripId.value,
    "distanceWbxqy": val
  })
  await fetchData()
}
// 司机确认已返程
const returned = async () => {
  await returnedAAA()
  uni.showToast({
    title: "确认返程,准备就绪!"
  })
  await fetchData()
}
const currentImageUrl = ref()
//图片
const select = (res) => {
  let {tempFiles, tempFilePaths} = res
  const filePath = res.tempFilePaths[0];
  console.log(tempFiles)
  console.log(tempFilePaths)
  uni.showLoading({
    title: '上传中...'
  });
  uni.uploadFile({
    url: "http://localhost:9999/upload", // 你的后端上传接口
    filePath: filePath,
    name: 'file', // 文件对应的 key，后端用这个 key 获取文件数据
    formData: {
      // 如果需要附加额外的参数，可以在这里定义
      token: 'your-authentication-token'
    },
    success: (uploadFileRes) => {
      currentImageUrl.value = JSON.parse(uploadFileRes.data).url
      console.log('上传成功', JSON.parse(uploadFileRes.data).url);
    },
    fail: (uploadFileRes) => {
      console.log('上传失败', uploadFileRes);
    },
    complete: () => {
      uni.hideLoading();
    }
  })
}
const success = (e) => {
  console.log(e)
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  padding: 20px;
}

.swiper {
  width: 100%;
  height: 200px;
  margin-bottom: 20px;
}

.swiper-image {
  width: 100%;
  height: 100%;
}


.CarRequest-card {
  display: flex;
  justify-content: space-between;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  margin-right: 10px;
}


.info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.username {
  font-size: 16px;
  font-weight: bold;
}

.details {
  font-size: 14px;
  color: #555;
}

.date {
  font-size: 12px;
  color: #999;
}

</style>
